package es.ceura.wilder.actions;

import es.ceura.wilder.datastructures.request.HTTPRequest;
import es.ceura.wilder.datastructures.response.HTTPResponse;
import es.ceura.wilder.handlers.HTTPResponseSender;
import es.ceura.wilder.logger.Logger;
import es.ceura.wilder.parsers.HTTPResponseParser;
import es.ceura.wilder.resources.DeniedAccesException;
import es.ceura.wilder.resources.InvalidResourceRequestException;
import java.io.IOException;
import java.net.Socket;

/**
 *
 * @author Jorge Madrid
 */
public class Get implements Action {

    public HTTPResponseParser responseParser;
    public HTTPResponseSender responseSender;

    public Get() {
        responseParser = new HTTPResponseParser();
        responseSender = new HTTPResponseSender();
    }

    @Override
    public void doAction(HTTPRequest request, Socket socket)
            throws DeniedAccesException {
        HTTPResponse response = null;
        try {
            response = responseParser.createHTTPResponse(request);

            responseSender.sendHTTPResponse(response, socket);

        } catch (IOException | InvalidResourceRequestException ex) {
            try {
                Logger.INSTANCE.logError("Error while trying to load resource -- ", ex);
                response = responseParser.createHTTPNotFound(request);
            } catch (IOException | InvalidResourceRequestException ex1) {
            }
        } finally {
            try {
                if (responseSender != null) {
                    responseSender.sendHTTPResponse(response, socket);
                }
            } catch (IOException ex) {
                Logger.INSTANCE.logError("Error while sending data..." + socket, ex);
            }
        }
    }
}
